package org.chaiyi.template.core.framework.support;

import org.chaiyi.template.core.common.supporter.Supporter;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import reactor.core.publisher.Mono;

import java.util.concurrent.ConcurrentHashMap;

public class SupporterCache<T extends Supporter> {
    private final ReactiveMongoOperations baseMongo;
    private final ConcurrentHashMap<String, Mono<T>> map = new ConcurrentHashMap<>();
    private final DefaultSupportManager defaultSupportManager;

    private final Class<T> ownerClass;

    private final String ownerName;

    public SupporterCache(Class<T> ownerClass, ReactiveMongoOperations baseMongo, DefaultSupportManager defaultSupportManager) {
        this.baseMongo = baseMongo;
        this.ownerClass = ownerClass;
        this.defaultSupportManager = defaultSupportManager;
        String simpleName = ownerClass.getSimpleName();
        ownerName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);

    }

    /**
     * 获取提供者，当提供者不在map中时查库，如果查库也不存在时查buDefaultMap，buDefaultMap还是没有则查询bu默认配置表
     */
    public Mono<T> getSupporter(String tenantId, String buCode) {
        return map.computeIfAbsent(getKey(tenantId, buCode),
                key -> baseMongo.findById(buCode, ownerClass, getCollectionName(tenantId))
                        .switchIfEmpty(defaultSupportManager.get(tenantId,buCode,ownerClass))
        );
    }

    private String getKey(String tenantId, String buCode) {
        return tenantId + "_" + buCode + "_" + ownerName;
    }


    private String getCollectionName(String tenantId) {
        return tenantId + "_" + ownerName;
    }
}
